<template>
  <a-modal
    title="授权项目"
    :width="800"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-card :bordered="false">
      <div>
        <a-transfer
          class="tree-transfer"
          :data-source="dataSource"
          :target-keys="targetKeys"
          :render="item => item.title"
          :show-select-all="false"
          @change="onChange"
        >
          <template slot="children" slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
            <a-tree
              v-if="direction === 'left'"
              blockNode
              checkable
              checkStrictly
              defaultExpandAll
              :checkedKeys="[...selectedKeys, ...targetKeys]"
              :treeData="treeData"
              @check="
                (_, props) => {
                  onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect)
                }
              "
              @select="
                (_, props) => {
                  onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect)
                }
              "
            />
          </template>
        </a-transfer>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import { sysUserOwnProject, sysUserGrantProject } from '@/api/modular/system/userManage'
import { getProjectTree } from '@/api/modular/main/project'

function isChecked(selectedKeys, eventKey) {
  return selectedKeys.indexOf(eventKey) !== -1
}

function handleTreeData(data, targetKeys = []) {
  data.forEach(item => {
    item['disabled'] = targetKeys.includes(item.key)
    if (item.children) {
      handleTreeData(item.children, targetKeys)
    }
  })
  return data
}

export default {
  name: 'UserProjectIndex',

  data() {
    return {
      targetKeys: [],
      dataSource: [],
      visible: false,
      confirmLoading: false,
      projectTree: []
    }
  },
  computed: {
    treeData() {
      return handleTreeData(this.projectTree, this.targetKeys)
    }
  },
  methods: {
    onChange(targetKeys) {
      console.log('Target Keys:', targetKeys)
      this.targetKeys = targetKeys
    },
    onChecked(_, e, checkedKeys, itemSelect) {
      const { eventKey } = e.node
      itemSelect(eventKey, !isChecked(checkedKeys, eventKey))
    },
    //初始化方法
    userRole(record) {
      this.recordEntity = record
      this.visible = true
      //加载已有数据
      this.sysUserOwnRole()

      // 获取项目树
      getProjectTree().then(res => {
        this.projectTree = res.data

        const transferDataSource = []
        function flatten(list = []) {
          list.forEach(item => {
            transferDataSource.push(item)
            flatten(item.children)
          })
        }
        flatten(JSON.parse(JSON.stringify(res.data)))
        this.dataSource = transferDataSource
      })
    },
    /**
     * 获取用户已有角色
     */
    sysUserOwnRole() {
      this.loading = true
      sysUserOwnProject({ id: this.recordEntity.id }).then(res => {
        //选中多选框
        this.targetKeys = res.data
        this.loading = false
      })
    },

    handleSubmit() {
      this.confirmLoading = false
      this.visible = false
      sysUserGrantProject({ id: this.recordEntity.id, grantProjectIdList: this.targetKeys })
        .then(res => {
          if (res.success) {
            this.$message.success('授权成功')
            this.confirmLoading = false
            this.$emit('ok', this.recordEntity)
            this.handleCancel()
          } else {
            this.$message.error('授权失败：' + res.message)
          }
        })
        .finally(res => {
          this.confirmLoading = false
        })
    },
    handleCancel() {
      this.recordEntity = []
      this.targetKeys = []
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-transfer-customize-list .ant-transfer-list {
  width: 0;
}
/deep/.ant-transfer-list {
  max-height: 320px;
  .ant-transfer-list-body {
    overflow: auto;
  }
}
</style>
